package git.soulbgm.service.impl;

import git.soulbgm.common.base.BaseServiceImpl;
import git.soulbgm.mapper.GoodsMapper;
import git.soulbgm.pojo.Goods;
import git.soulbgm.service.GoodsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品表
 *
 * @author SoulBGM
 * @version V1.0
 * @date 2020-11-06 17:27:16
 */
@Service
public class GoodsServiceImpl extends BaseServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public boolean reduceInventory(Long goodsId, Integer amount) throws Exception {
        Goods goods = findById(goodsId);
        // 检查库存
        checkInventory(goods, amount);
        // 扣减库存
        goods.setInventory(goods.getInventory() - 1);
        return update(goods);
    }

    private void checkInventory(Goods goods, Integer amount) throws Exception {
        Integer inventory = goods.getInventory();
        if (inventory < amount) {
            throw new Exception("库存不足");
        }
    }

}